package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.StrategyContent;
import cn.wolfcode.trip.base.domain.StrategyDetail;
import cn.wolfcode.trip.base.mapper.StrategyContentMapper;
import cn.wolfcode.trip.base.mapper.StrategyDetailMapper;
import cn.wolfcode.trip.base.query.StrategyDetailQueryObject;
import cn.wolfcode.trip.base.service.IStrategyDetailService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;


@Service
public class StrategyDetailServiceImpl implements IStrategyDetailService {

    @Autowired
    private StrategyDetailMapper detailMapper;
    @Autowired
    private StrategyContentMapper contentMapper;

    public PageInfo selectForList(StrategyDetailQueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List list = detailMapper.selectForList(qo);
        return new PageInfo(list);
    }

    /**
     * 序号为null的情况,设置自增序号
     * 判断状态是否发布,设置发布时间
     * 保存之前设置创建时间
     * 添加和更新攻略管理
     * 添加和更新攻略文章
     * @param strategyDetail
     */
    public void saveOrUpdate(StrategyDetail strategyDetail) {

        //数据库查询每个catalog攻略下最大的排序
        if (strategyDetail.getSequence() == null) {
            Integer maxSequence = detailMapper.getMaxSequence(strategyDetail.getCatalog().getId());
            //如果用户不设置,就自增
            strategyDetail.setSequence(maxSequence + 1);
        }
        //判断是否发布状态
        if (strategyDetail.getState() == StrategyDetail.STATE_RELEASE) {
            strategyDetail.setReleaseTime(new Date());
        }
        //获取文本对象
        StrategyContent content = strategyDetail.getStrategyContent();

        if (strategyDetail.getId() != null) {
            detailMapper.updateByPrimaryKey(strategyDetail);
            //文本更新
            content.setId(strategyDetail.getId());
            contentMapper.updateByPrimaryKey(content);
        } else {
            //保存之前要新建发布时间
            strategyDetail.setCreateTime(new Date());
            detailMapper.insert(strategyDetail);

            content.setId(strategyDetail.getId());
            contentMapper.insert(content);
        }
    }

    public StrategyContent getContentById(Long id) {
        return contentMapper.selectByPrimaryKey(id);
    }

    public StrategyDetail getByDetailId(Long id) {
        return detailMapper.selectByPrimaryKey(id);
    }
}
